<template>
  <div>
    <div id="mapContainer" :style="{height:height+'px'}"></div>
    <div class="topMenu">
      <div style="display: inline-block" class="menuWrap">
        <table>
          <tbody>
          <tr>
            <td style="padding-right: 5px">
              <lbtn  @click="startPoint(startText)"  type="primary">{{startText}}</lbtn >
            </td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="rightPanel">
      <div>
        <div>
          <table class="pdTb">
            <tbody>
            <tr>
              <td></td>
              <td>区域名称</td>
<!--              <td>车辆</td>-->
              <td style="text-align: center">终端数</td>
              <td style="width: 30px">

              </td>
            </tr>
            <tr v-for="(item,index) in  areas" :key="index">
              <td >{{index + 1}}</td>
              <td>
                <ltext v-model="item.name" />
              </td>
              <td style="text-align: center;width: 100px;"><a title="点击查看明细" class="tersA" >{{item.qty}}</a></td>
              <td style="text-align: center">
                <i style="cursor:pointer;" class="fa fa-trash" @click="delArea(index)"   title="删除" />
              </td>
            </tr>
            </tbody>
          </table>
        </div>
        <div style="text-align: center; margin-top: 20px;">
          <lbtn  type="primary"  @click="saveAreaName" :loading="saveLoading">保存设置</lbtn >
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import tool from "@/utils/tool";
export default {
  name: "block",
  data() {
    return {
      title: '',
      showModal: false,
      height: window.innerHeight - 70,
      customers: [],
      value: 13,
      mouseTool: null,
      map: null,
      overlays:[],
      areas: [],
      onePath: [],
      polylines: [],
      polylinesEdit: [],
      saveLoading: false,
      startBtn: false,
      carList: [],
      unPointList: [],
      startText: '开始标记',
      simpleMark:[],
      popCusList: [],
      centerPoint: []
    }
  },
  mounted() {
    this.getLngLat()
    this.getCar()
  },
  methods: {
    open (title) {
      this.title = title
      this.showModal = true
    },
    getCar() {
      tool.post('deliver/getCar',{}).then(ret => {
        if(ret.stat && ret.data && ret.data.length > 0) {
          let cars = []
          for (let i = 0; i < ret.data.length; i++) {
            cars.push({label: ret.data[i].name, value: ret.data[i].id})
          }
          this.carList = cars
        }
      })
    },
    edLine () {

    },
    // 显示该路线下所有终端列表
    showCustomers(index) {
      this.popCusList = this.areas[index].cus
      this.$refs.popCus.open({title:'区域内客户明细'})
    },
    // 未定位终端
    getUnPoint () {
      tool.post('deliver/getUnPoint',{}).then(ret=>{
        if(ret.stat) {
          this.unPointList = ret.data
        }
      })
    },
    // 开始标记
    startPoint (startText) {
      if(startText === '开始标记') {
        this.mouseTool.polyline({
          strokeColor:'#80d8ff'
        })
        this.startText = '结束标记'
      } else {
        this.mouseTool.close(true)
        this.startText = '开始标记'
      }
    },
    clearPoint () {
      this.map.remove(this.overlays)
      this.overlays = []
    },
    // 查询 客户经纬度
    getLngLat () {
      tool.post('deliver/getLngLat',{}).then(ret=>{
        if(ret.stat) {
          this.customers = ret.data.list
          this.centerPoint = ret.data.center
          this.showMap(this.centerPoint)
        }
      })
    },
    loadMap (arrs) {
      var style =
          {
            url: 'https://a.amap.com/jsapi_demos/static/images/mass0.png',
            anchor: new AMap.Pixel(6, 6),
            size: new AMap.Size(11, 11)
          }

      var mass = new AMap.MassMarks(arrs, {
        opacity: 0.8,
        zIndex: 111,
        cursor: 'pointer',
        style: style
      })

      var marker = new AMap.Marker({content: ' ', map: this.map});

      mass.on('mouseover', function (e) {
        marker.setPosition(e.data.lnglat);
        marker.setLabel({content: e.data.name})
      })
      mass.setMap(this.map)
      this.map.plugin(["AMap.MouseTool"], ()=>{
        this.mouseTool = new AMap.MouseTool(this.map)
        this.mouseTool.on('draw', (e)=>{
          this.overlays.push(e.obj)
        })
        //使用鼠标工具，在地图上画标记点
        this.mouseTool.polyline({
          strokeColor:'#80d8ff'
        })
        AMap.event.addListener( this.mouseTool,'draw',(e)=>{
          let path = e.obj.getPath()
          let arrs = []
          for (let i in path) {
            arrs.push(new AMap.LngLat(path[i].lng,path[i].lat))
          }
          this.addArea(path)
        })
      })
      this.getArea()
    },
    showMap (center) {
      this.map = new AMap.Map('mapContainer', {
        zoom: 13,
        center: center,
      })

      let arrs = []
      for (let i = 0; i < this.customers.length; i++) {
        let lng = Number(this.customers[i].longitude)
        let lat = Number(this.customers[i].latitude)
        let id = Number(this.customers[i].id)
        //  let ar = {name: this.customers[i].title, lnglat:{lng:lng,Q:lng,P:lat,lat:lat}}
        let ar = {lnglat:[lng,lat],name: this.customers[i].title, id: id}
        arrs.push(ar)
      }
      this.loadMap(arrs)
      setTimeout(()=>{
        this.addStorePoint()
      },500)
    },
    // 加仓库标记
    addStorePoint () {
      AMapUI.loadUI(['overlay/SimpleMarker'],  (SimpleMarker)=> {
        new SimpleMarker({
          //前景文字
          iconLabel: {
            innerHTML: '<span>仓库</span>',
            style: {
              color:'white'
            }
          },
          //图标主题
          iconTheme: 'default',
          //背景图标样式
          iconStyle: 'blue',
          map: this.map,
          position: this.centerPoint
        })
      })
    },
    // 增加区域
    addArea(path) {
      this.pointInPath(path)
    },
    // 保存区域名称
    saveAreaName() {
      let arr = this.areas.filter(row => {
        return row.name
      })
      if(arr.length > 0) {
        tool.post('deliver/saveAreaName', {arr: arr}).then(ret => {})
      } else {
        tool.err('请输入区域名称')
      }
    },
    // 点是否在多边形区域内
    pointInPath(path){
      tool.post('deliver/saveArea',{path:path}).then(ret=>{
        if(ret.stat) {
          this.clearPoint()
          this.getArea()
        }
      })
    },
    // 数据库删除区域块
    delArea (index) {
      tool.confirm('确定删除区域?').then(() => {
        tool.post('deliver/delAreaById',{id: this.areas[index].id}).then(ret => {
          if(ret.stat) {
            this.getArea()
          }
        })
      })
    },
    // 取所有区域
    getArea() {
      this.removeSimpleMark()
      tool.post('deliver/getAreaList',{}).then(ret=>{
        if(ret.stat) {
          this.onePath = ret.data
          let ar = []
          for(let i in ret.data) {
            let path = []
            if (ret.data[i].path) {
              path = JSON.parse(ret.data[i].path)
            }
            if (path.length === 0) {continue}
            let paths = []
            for (let x in path) {
              paths.push(new AMap.LngLat(path[x].lng,path[x].lat))
            }
            this.addPoint(path[path.length-1].lng,path[path.length-1].lat,Number(i)+1)
            let color = 'black'
            this.polylines[i] = new AMap.Polyline({
              path: paths,
              strokeColor:color,
              strokeOpacity:0.4,
              strokeWeight:3,
              strokeStyle:"dashed",
              strokeDasharray:[10,5]
            })
            this.polylines[i].setMap(this.map)
            // this.map.add(this.polylines[i]) // 与上一行代码功能重复
            this.polylines[i].on('click',  (e) =>{
              tool.err(ret.data[i].name?ret.data[i].name:'未定义区域名称')
            })
            //
            let pa = []
            for ( let i in path) {
              pa.push([path[i].lng,path[i].lat])
            }
            let cc = this.getTerQty(pa)
            ar.push({
              id:ret.data[i].id,
              name:ret.data[i].name,
              qty:cc[0],
              color:color,
              licence:ret.data[i].z_cars_id,
              cus: cc[1]
            })
          }
          this.areas = ar
          this.mouseTool.close(true)
          this.startText = '开始标记'
          this.edLine()
        }
      })
    },
    // 计算区域中的终端数量
    getTerQty(path) {
      let c = 0
      let cus = []
      for (let i in this.customers) {
        let lng = this.customers[i].longitude
        let lat = this.customers[i].latitude
        if(lng && lat) {
          let point = [lng,lat]
          let isPointInRing = AMap.GeometryUtil.isPointInRing(point,path)

          if(isPointInRing) {
            c++
            cus.push(this.customers[i])
          }
        }
      }
      return [c, cus]
    },
    // 地图上删除区域块
    removeSimpleMark (index) {
      if(typeof index === "undefined") {
        this.map.remove(this.polylines)
        this.polylines = []
        this.map.remove(this.simpleMark)
        this.simpleMark = []
      } else {
        // 删除点标志
        this.map.remove(this.simpleMark[index])
        this.simpleMark.splice(index, 1)
        // 删除区域
        this.map.remove(this.polylines[index])
        this.areas.splice(index,1)
        this.polylines.splice(index,1)
      }
    },
    // 加区域点
    addPoint (lng,lat,title) {
      AMapUI.loadUI(['overlay/SimpleMarker'],  (SimpleMarker)=> {
        //创建SimpleMarker实例
        let sm = new SimpleMarker({
          //前景文字
          iconLabel: {
            innerHTML: '<span>'+title+'</span>',
            style: {
              color:'white'
            }
          },
          //图标主题
          iconTheme: 'default',
          //背景图标样式
          iconStyle: 'blue',
          //...其他Marker选项...，不包括content
          map: this.map,
          position: [lng, lat]
        })
        this.simpleMark.push(sm)
      })
    },
  }
}
</script>
<style scoped>
#mapContainer {
  width: 100%;
  height: 300px;
}
.topMenu {
  position: absolute;
  top: 10px;
  left: 0;
  right: 0;
  text-align: center;
}
.menuWrap {
  padding: 5px;
}
.menuWrap td{padding-left: 5px}
.rightPanel {
  background-color: white;
  position: fixed;
  right: 10px;
  top: 150px;
  padding: 0 5px 5px 5px;
  max-height: 800px;
  text-align: center;
  overflow: auto;
}
.pdTb {
  margin-top: 10px;
}
.pdTb td {
  border: 1px solid #dcdee2;
  padding: 2px;
}
.tersA:hover{
  text-decoration: underline;
}
</style>
